#include "battery_app.h"
#include "battery_board.h"

#if ((_BOARD_TYPE_ != _V32_B_BOARD_) && ((_BOARD_TYPE_ & _DA01_BOARD_) != _DA01_BOARD_))
/**
 * @brief 获取输入电压
 *
 * @return uint32_t - 电压系数（毫伏为单位）
 */
static uint32_t BatteryGetBatteryVoltage(void);

static BatteryStatusBit_t BatteryStatusBit = {0};

static uint32_t BatteryGetBatteryVoltage(void)
{
  uint32_t Summation = 0, TmpValue = 0;
  uint32_t BatterySamplingBuff[BATTERY_VOLTAGE_DETECTION_SAMPLING] = {0};

  for (uint8_t i = 0; i < BATTERY_VOLTAGE_DETECTION_SAMPLING; i++)
  {
    BatterySamplingBuff[i] = BatteryGetInputVoltage();
  }

  for (uint8_t i = 0; i < BATTERY_VOLTAGE_DETECTION_SAMPLING - 1; i++)
  {
    for (uint8_t j = i + 1; j < BATTERY_VOLTAGE_DETECTION_SAMPLING; j++)
    {
      if (BatterySamplingBuff[i] > BatterySamplingBuff[j])
      {
        TmpValue = BatterySamplingBuff[i];
        BatterySamplingBuff[i] = BatterySamplingBuff[j];
        BatterySamplingBuff[j] = TmpValue;
      }
    }
  }

  for (uint8_t i = ADC_SAMPLING_CALCULATE_OFFSET; i < (BATTERY_VOLTAGE_DETECTION_SAMPLING - ADC_SAMPLING_CALCULATE_OFFSET); i++)
  {
    Summation += BatterySamplingBuff[i];
  }

  return (uint32_t)(Summation / (BATTERY_VOLTAGE_DETECTION_SAMPLING - (ADC_SAMPLING_CALCULATE_OFFSET * 2)));
}
#endif

uint8_t BatteryGetVoltagePercentage(void)
{
#if ((_BOARD_TYPE_ != _V32_B_BOARD_) && ((_BOARD_TYPE_ & _DA01_BOARD_) != _DA01_BOARD_) && ((_BOARD_TYPE_ & _EC01_BOARD_) != _EC01_BOARD_))
  return BatteryStatusBit.PercentageOfElectricity;

#else
  return 100;
#endif
}

void BatteryStartGetPercentageOfElectricity(void)
{
#if ((_BOARD_TYPE_ != _V32_B_BOARD_) && ((_BOARD_TYPE_ & _DA01_BOARD_) != _DA01_BOARD_) && ((_BOARD_TYPE_ & _EC01_BOARD_) != _EC01_BOARD_))
  BatteryEnableDetection();
  BatteryDelayMs(WAIT_VOLTAGE_STABILISATION_TIME);

  uint32_t BatteryVoltage = BatteryGetBatteryVoltage();
  PRINT("[battery]: battery voltage: %d.\r\n", BatteryVoltage);

  if (BatteryVoltage > BATTERT_MIXIMUM_VOLTAGE)
  {
    BatteryStatusBit.PercentageOfElectricity = BATTERY_ELECTRICITY_CONVERSION(BatteryVoltage);
    if (BatteryStatusBit.PercentageOfElectricity > 100)
    {
      BatteryStatusBit.PercentageOfElectricity = 100;
    }
  }

  BatteryDisableDetection();
  PRINT("[battery]: current remaining power: %d.\r\n", BatteryStatusBit.PercentageOfElectricity);
#endif
}

void BatteryConfiguration(void)
{
#if ((_BOARD_TYPE_ != _V32_B_BOARD_) && ((_BOARD_TYPE_ & _DA01_BOARD_) != _DA01_BOARD_) && ((_BOARD_TYPE_ & _EC01_BOARD_) != _EC01_BOARD_))
  BatteryBoardInitialisation();
#endif
}
